package com.mchat.common.controller;

import com.mchat.common.domain.FileHash;
import com.mchat.common.service.CommonService;
import com.mchat.exceptions.CommonException;
import com.mchat.util.JsonUtil;
import com.mchat.util.MailUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import reactor.kafka.sender.KafkaSender;
import reactor.kafka.sender.SenderOptions;
import reactor.kafka.sender.SenderRecord;

import java.util.Map;

import static com.mchat.util.Utils.getUid;


@RestController
public class CommonController {

    private final CommonService commonService;

    public CommonController(CommonService commonService, JsonUtil jsonUtil, SenderOptions<Long, String> senderOptions) {
        this.commonService = commonService;
        this.jsonUtil = jsonUtil;
        this.sender = KafkaSender.create(senderOptions);
    }

    private final JsonUtil jsonUtil;
    private final KafkaSender<Long,String> sender;

    @GetMapping("/avatar")
    public Map getPreSignedURL(ServerWebExchange exchange) {
        return commonService.getPreSignedURL(getUid(exchange));
    }



    /**
     * 发送邮件验证码
     */
    @GetMapping("/send-code")
    public Mono<Void>sendCode(@RequestParam String email){
//       参数合法性校验
        if(email==null||email.isEmpty()||!MailUtil.isValid(email)){
            return Mono.error(new CommonException("邮箱格式错误"));
        }
        return commonService.sendCode(email);
    }

    /**
     * 上传文件后将文件的hash和名称上传实现文件秒传
     */
    @PutMapping("/uploadHash")
    public Mono<Void> uploadFileHash(@RequestBody FileHash dto){
        return sender
                .send(Mono.just(SenderRecord.create("file-hash",null,null,null,jsonUtil.toStr(dto),null)))
                .doOnNext(result->{
                    Exception exception = result.exception();
                    if(exception !=null)
                        throw new CommonException(exception.getMessage(),500,"发送失败");
                }).then();
    }


}
